<?php
/**
 * 订单类.
 * User: chan
 * Date: 2017/9/28 19:24
 */

namespace app\api\logic;

use app\api\BaseModel;
use app\api\logic\Order;
use app\api\model\DriverOrderInfo;
use app\api\model\OrderGoods as OrderGoodsModel;

class Orderreturn extends BaseModel
{
    /**
     * 回调地址
     */
    public function query_notify_url()
    {
        $params = array();
        foreach($_POST as $key=>$val) {
            //动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
            $params[$key] = $val;
        }
        if(count($params)<1){//如果参数为空,则不进行处理
            die('error!');
        }

        //调取支付接口
        $allinpay =  new \app\api\service\Allinpay();

        if($allinpay->validSign($params)){//验签成功
            //此处进行业务逻辑处理
            if($params['trxstatus'] == '0000'){

                $order = db('order')->where(['order_sn'=>$params['cusorderid']])->find();
                if(empty($order))return false;

                //查询是否有自提佣金
                $order_where['id'] = $order['shop_id'];
                $shop_result=db("shop")->where($order_where)->find();
                if(!empty($shop_result['cmomission_mention']) && ($order['type'] == '2' || $order['type'] == '4')){
                    $mention_balance_where['order_id'] = $order['id'];
                    $mention_balance = db('mention_balance')->where($mention_balance_where)->find();
                    if($shop_result['cmomission_mention'] != '0.00' && empty($mention_balance)){
                        $mention_balance_insert['uid'] = $order['user_id'];
                        $mention_balance_insert['shop_id'] = $order['shop_id'];
                        $mention_balance_insert['order_id'] = $order['id'];
                        $mention_balance_insert['commission_record'] = $shop_result['cmomission_mention'];
                        $mention_balance_insert['money'] = $shop_result['cmomission_mention'];
                        db('mention_balance')->insert($mention_balance_insert);
                    }
                }

                db('order')->where(['order_sn'=>$params['cusorderid']])->update(['status'=>'1','pay_time'=>TIMESTAMP]);
                
                //库存更新
                $products = db('order_goods')->where(['order_id'=>$order['id']])->select();
                if (!empty($products)) {
                    //删减库存
                    foreach($products as $v){
                        if(!empty($v['spec_id'])){
                            db('goods_option')->where(['id'=>$v['spec_id']])->setDec('stock',$v['goods_num']);
                        }else{
                            db('goods')->where(['id'=>$v['goods_id']])->setDec('stock',$v['goods_num']);
                        }
                    }
                }
                /*更新司机配送订单*/
                //$this->upateDriverordInfo($order,$order['send_time']);

                $printer = db('printer')->where(['shop_id'=>$order['shop_id'],'printer_type'=>'1'])->find();
                $printer = explode("#", $printer['printer_id']);

                $member = db('member')->where(['id'=>$order['user_id']])->field('nickname')->find();

                if(!empty($printer[0])) {
                    //打印订单
                    $param['snlist'] = $printer[0];
                    $param['shopid'] = $order['shop_id'];
                    $param['shipping_address'] = $order['address'];
                    $param['mobile'] = $order['mobile'];
                    $param['order_id'] = $order['id'];
                    $param['realname'] = $member['nickname'];
                    $wp_print = new \app\api\logic\System();
                    $wp_print->wp_print($param);
                }

                $printer = db('printer')->where(['shop_id'=>$order['shop_id'],'printer_type'=>'2'])->find();
                $printer = explode("#", $printer['printer_id']);

                if(!empty($printer[0])) {
                    $param['snlist'] = $printer[0];
                    $wp_print->wp_receipt_print($param);
                }
            }
        }
        else{
            die('非法调用!');
        }
    }

    public function upateDriverordInfo($order_result,$send_time)
    {
        $route_where['shop_id'] = $order_result['shop_id'];
        $route_where['id'] = $order_result['route_id'];

        $driver_order_where['route_id'] = $order_result['route_id'];
        $driver_order_where['shop_id'] = $order_result['shop_id'];
        $driver_order_where['send_time'] = $send_time;
        $driver_order = db('driver_order')->where($driver_order_where)->find();
        if(!empty($driver_order)){//是否有该店铺这条配送线路在该时间段的订单存在
            $dorder_data['num'] = $this->getSendNum($order_result['route_id'], $driver_order['id']);
            $dorder_data['order_id'] = $order_result['id'];
            $dorder_data['driver_order_id'] = $driver_order['id'];
            $dorder_data['route_address_id'] = $order_result['route_address_id'];
            //插入新订单
            db('driver_order_info')->insert($dorder_data);
            //更新之前 订单排序
            $this->updateinfo($driver_order['id'], $order_result['shop_id']);

        }else{
            $driver_id = db('route')->where($route_where)->value('driver_id');
            if($driver_id){
                $driver_order_where['driver_id'] = $driver_id;
            }
            $driver_order_where['driver_order_sn'] = Order::generateOrderNo();
            db('driver_order')->insert($driver_order_where);
            $driver_order_id = db('driver_order')->getLastInsID();
            $dorder_info_data['order_id'] = $order_result['id'];
            $dorder_info_data['driver_order_id'] = $driver_order_id;
            $dorder_info_data['num'] = 1;
            db('driver_order_info')->insert($dorder_info_data);
        }
    }

    public function updateinfo($id, $shopid)
    {
        $search = [];//查出的存放点
        $shop = db('shop')->where(['id'=>$shopid])->field('lat,lng')->find();
        //['lat'=>123.22,'lng'=>143.55];
        $top = $shop;//仓库点

        //筛选的数据
        $where['shop_id']=$shopid;
        $where['id'] = $id;
//        $uid = 3;
        $driverorder = db('driver_order')->where($where)->find();
//        echo db('driver_order')->getLastSql();
        if(empty($driverorder))return ['message'=>'参数有误'];

        $ar = db('driver_order_info')->alias('do')
            ->join('order o', 'o.id = do.order_id')
            ->where(['do.driver_order_id'=>$id])
            ->field('do.*,o.lat,o.lng')
            ->select();

        $lenght = count($ar);
        if($lenght == 1){
            $ar[0]['dif'] = getDistance($top['lat'],$top['lng'],$ar[0]['lat'],$ar[0]['lng']);
            $search=$ar;
        }else{
            for($i=0; $i<$lenght;$i++){
                //找出第一点
                foreach($ar as $k=>&$v){
                    //计算距离
                    $v['dif'] = getDistance($top['lat'],$top['lng'],$v['lat'],$v['lng']);
                    // $v['dif'] = $v['a'] * $v['b'] - $top['a']*$top['b'];
                    $dif[$k] = $v['dif'];
                }
                array_multisort($dif, SORT_ASC, SORT_NUMERIC, $ar);
                $search[] = $ar[0];
                $top = $ar[0];
                unset($dif);
                unset($ar[0]);
            }

        }

//        var_dump($search);die;
        if(!empty($search)){
            foreach ($search as $key => $value) {
                $data[$key]['id'] = $value['id'];
                $data[$key]['num'] = $key+1;
                $distance = round($value['dif']/1000,2);
                $data[$key]['distance'] = $distance;
            }
//            var_dump($data);die;
            $driver_order_info = new DriverOrderInfo();
            $res = $driver_order_info->saveAll($data);
            if(!$res)return false;
            return true;
        }
    }

    public function getSendNum($order_id, $driver_order_id)
    {
        if(!isset($order_id))return false;
        if(!isset($driver_order_id))return false;
        $order = db('order')->where(['id'=>$order_id])->find();
        $driver_order = db('driver_order')->where(['id'=>$driver_order_id])->find();
        if(empty($order) || empty($driver_order))return ['message'=>'订单不存在！'];

        //离商家多远？
        $shop = db('shop')->where(['id'=>$order['shop_id']])->field('lng,lat')->find();
        $lng1 = $shop['lng'];
        $lat1 = $shop['lat'];
        $lng_i = $order['lng'];
        $lat_i = $order['lat'];
        $distance = getDistance($lat1,$lng1, $lat_i,$lng_i);
//var_dump($distance);die;
        $driver_order_count = db('driver_order_info')->where(['driver_order_id'=>$driver_order_id])->count();
        $driver_order_infos = db('driver_order_info')->where(['driver_order_id'=>$driver_order_id])->order('num asc')->select();

        foreach($driver_order_infos as $key=>&$value){
            $order_address = db('order')->where(['id'=>$value['order_id']])->field('lng,lat')->find();
//            echo db('order')->getLastSql();
            $lng_next = $order_address['lng'];
            $lat_next = $order_address['lat'];
            if($key==0){
                $value['distance'] = getDistance($lat1,$lng1, $lat_next,$lng_next);
                if($value['distance']>$distance){
                    $topval = $value;
                    break;
                }
            }else{
                //2-3-4-5....离上一个的点信息的距离
                $driver_order_info_before = $driver_order_infos[$key-1];
                $b_lng = $driver_order_info_before['lng'];
                $b_lat = $driver_order_info_before['lat'];
                $value['distance'] = getDistance($b_lat,$b_lng, $lat_next,$lng_next);

                //插入点离上一个信息点的距离
                $distance_i = getDistance($b_lat,$b_lng, $lat_i,$lng_i);
                if($distance_i<$value['distance']){
                    $topval = $value;
                    break;
                }
            }
        }

        if(!empty($topval)){
            $num = $topval['num'];
            return $num;
        }else{
            $num = $driver_order_count + 1;
            return $num;
        }
    }


}